import styles from "./SignInForm.module.css";
import { Form, Input, Button, Checkbox } from "antd";
// 1. 引入reducer 相关的hooks
import { signIn } from "@/redux/user/slice";
import { useSelector, useDispatch } from "@/redux/hooks";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export const SignInForm = () => {
  // 2. 获取redux里面的state
  const loading = useSelector((state) => state.user.loading);
  const token = useSelector((state) => state.user.token);
  // const error = useSelector((state) => state.user.error);

  // 3. 获取dispatch函数进行调用action
  const dispatch = useDispatch();

  const navigate = useNavigate();

  // 4. 使用effect监听token 在token更新的时候 判断是否登录
  useEffect(() => {
    if (token) {
      navigate("/");
    }
  }, [token]);

  const onFinish = (values: any) => {
    console.log("Success:", values);
    // 发送异步请求
    dispatch(signIn({ email: values.username, password: values.password }));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Form
      {...layout}
      name="basic"
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      className={styles["register-form"]}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[{ required: true, message: "Please input your username!" }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[{ required: true, message: "Please input your password!" }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>记住我</Checkbox>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit" loading={loading}>
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};
